

<script lang="ts" setup>
import { ref, computed, onMounted, watch } from 'vue';
import * as echarts from 'echarts';

// 定义 props
const props = defineProps({
  speed: {
    type: Number,
    default: 0
  },
  width: {
    type: String,
    default: '100%'
  },
  height: {
    type: String,
    default: '100%'
  },
  speedUnion: {
    type: String,
    default: 'km'
  },
  uid: {
    type: String,
    default: 'speed-gauge'
  }
});

// 定义响应式数据
const echartInstance = ref(null);

// 计算属性
const speedUnioText = computed(() => {
  return props.speedUnion === 'km' ? `{b|${props.speedUnion}/h}` : `{b|mph}`;
});

const eOption = computed(() => {
  return {
    series: [
      {
        type: 'gauge',
        name: 'Pressure',
        min: 0,
        max: 240,
        startAngle: 210,
        endAngle: -30,
        axisLine: {
          //外轮廓
          lineStyle: {
            width: 1,
            color: [
              [props.speed / 240, '#0091F0'],
              [1, '#C8C8C8']
            ]
          }
        },
        axisTick: {
          //刻度
          distance: -10,
          length: 5,
          splitNumber: 4,
          lineStyle: {
            //动态
            color: 'auto',
            width: 1
          }
        },
        splitLine: {
          //分割刻度
          length: 10,
          lineStyle: {
            color: '#C8C8C8',
            width: 1
          }
        },
        axisLabel: {
          show: false
        },
        pointer: {
          show: false,
          showAbove: true,
          width: 2,
          itemStyle: {
            color: '#0091F0'
          },
          length: '70%'
          // offsetCenter: [20, '20%']
        },
        detail: {
          valueAnimation: true,
          formatter: [`{a|${props.speed.toFixed(1)}}`, speedUnioText.value].join('\n'),
          color: '#000000',
          fontSize: 12,
          offsetCenter: [0, 5],
          rich: {
            a: {
              color: '#0091F0',
              fontSize: 18,
              fontWeight: 'bold'
            },
            b: {
              color: '#C8C8C8',
              fontSize: 12
            }
          }
        },
        data: [
          {
            value: props.speed
          }
        ]
      }
    ]
  };
});

// 初始化仪表盘
const initSpeedGauge = () => {
  const el = document.getElementById(props.uid);
  if (el) {
    const myChart = echarts.init(el);
    echartInstance.value = myChart;
    myChart.setOption(eOption.value);
    myChart.resize();
  }
};

// 监听 uid 和 eOption 的变化
watch(() => props.uid, (val:string, oldVal:string) => {
  if (val !== oldVal) {
    initSpeedGauge();
  }
});

watch(eOption, () => {
  initSpeedGauge();
});

// 挂载时初始化
onMounted(() => {
  initSpeedGauge();
});
</script>
<template>
  <div :id="uid" :style="{ width: width, height: height }"></div>
</template>
